package com.tianbing.adlottery.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSenderImpl;

public class EmailUtil {
	static Logger logger = Logger.getLogger(EmailUtil.class.getName());

	private JavaMailSenderImpl mailSender;

	private static final String DEFAULT_CHAR_ENCODING = "UTF-8";// "ISO-8859-1";

	private String characterEncoding = DEFAULT_CHAR_ENCODING;

	public EmailUtil() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 * @param toName
	 * @param toEmail
	 * @param fromName
	 * @param fromEmail
	 * @param subject
	 * @param textBody
	 * @param htmlBody
	 */
	public void sendMessage(String toName, String toEmail, String fromName, String fromEmail, String subject,
			String textBody, String htmlBody) {
		// Check for errors in the given fields:
		if (toEmail == null || fromEmail == null || subject == null || (textBody == null && htmlBody == null)) {
			logger.error("Error sending email in EmailTask.java: Invalid fields: "
					+ ((toEmail == null) ? "toEmail " : "") + ((fromEmail == null) ? "fromEmail " : "")
					+ ((subject == null) ? "subject " : "")
					+ ((textBody == null && htmlBody == null) ? "textBody or htmlBody " : ""));
		} else {
			try {
				// Use the global Jive encoding for the emails.
				String encoding = MimeUtility.mimeCharset(characterEncoding);
				MimeMessage message = mailSender.createMimeMessage();
				Address to = null;
				Address from = null;
				Address[] toS = null;
				if (toName != null) {
					to = new InternetAddress(toEmail, toName, encoding);
				} else {
					if (toEmail.indexOf(",") > 0) {
						String[] toAddr = toEmail.split(",");
						toS = new Address[toAddr.length];
						for (int i = 0; i < toAddr.length; i++) {
							toS[i] = new InternetAddress(toAddr[i].trim(), "", encoding);
						}
					} else {
						to = new InternetAddress(toEmail, "", encoding);
					}
				}
				if (fromName != null) {
					from = new InternetAddress(fromEmail, fromName, encoding);
				} else {
					from = new InternetAddress(fromEmail, "", encoding);
				}
				// set the date on exported message to be the current date
				SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", java.util.Locale.US);
				// format.setTimeZone(JiveGlobals.getTimeZone());
				format.setTimeZone(TimeZone.getDefault());
				message.setHeader("Date", format.format(new Date()));
				// message.setHeader("Product-Transfer-Encoding", "8bit");
				message.setHeader("Product-Transfer-Encoding", "base64");
				if (toS != null && toS.length > 1) {
					message.setRecipients(Message.RecipientType.TO, toS);
				} else {
					message.setRecipient(Message.RecipientType.TO, to);
				}
				message.setFrom(from);
				message.setSubject(StringUtils.replace(subject, "\n", ""), encoding);
				// Create HTML, plain-text, or combination messagel
				if (textBody != null && htmlBody != null) {
					MimeMultipart content = new MimeMultipart("alternative");
					// Plain-text
					MimeBodyPart text = new MimeBodyPart();
					text.setText(textBody, encoding);
					text.setDisposition(Part.INLINE);
					content.addBodyPart(text);
					// HTML
					MimeBodyPart html = new MimeBodyPart();
					html.setContent(htmlBody, "text/html");
					html.setDisposition(Part.INLINE);
					content.addBodyPart(html);
					// Add multipart to message.
					message.setContent(content);
					message.setDisposition(Part.INLINE);
					// addMessage(message);
					mailSender.send(message);

				} else if (textBody != null) {
					MimeBodyPart bPart = new MimeBodyPart();
					bPart.setText(textBody, encoding);
					bPart.setDisposition(Part.INLINE);
					MimeMultipart mPart = new MimeMultipart();
					mPart.addBodyPart(bPart);
					message.setContent(mPart);
					message.setDisposition(Part.INLINE);
					// Add the message to the send list
					// addMessage(message);
					mailSender.send(message);
				} else if (htmlBody != null) {
					MimeBodyPart bPart = new MimeBodyPart();
					bPart.setContent(htmlBody, "text/html;charset=" + encoding);
					bPart.setDisposition(Part.INLINE);
					MimeMultipart mPart = new MimeMultipart();
					mPart.addBodyPart(bPart);
					message.setContent(mPart);
					message.setDisposition(Part.INLINE);
					// Add the message to the send list
					// addMessage(message);
					mailSender.send(message);
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e);
			}
		}
	}

	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}

	public void setCharacterEncoding(String characterEncoding) {
		this.characterEncoding = characterEncoding;
	}

}
